#include "udpmodule.h"
#include "ui_udpmodule.h"

UdpModule::UdpModule(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UdpModule)
{
    ui->setupUi(this);
    setFixedSize(this->width(),this->height());
    udpServerObject = new UDPServerClient(this);

    //默认测试数据信息
    ui->plainTextEdit_sendMsg->setPlainText("Hello udp protocol test.");



}

UdpModule::~UdpModule()
{
    delete ui;
}

//启动监听
void UdpModule::on_toolButton_start_clicked()
{
    ui->plainTextEdi_msgList->clear();
    //初始化 套接字 设置组播地址
    udpServerObject->udp_socket = new QUdpSocket;
    //获取组合列表框控件的ip地址
    QString ipAdr = ui->comboBox_ipAdr->currentText();
    udpServerObject->udp_hostAddress.setAddress(ipAdr);

    int port = ui->spinBox_port->text().toInt();

    //绑定本地IP和端口号
    udpServerObject->udp_socket->bind(port);
    //显示消息消息列表

    ui->plainTextEdi_msgList->appendPlainText("***********服务启动成功***********");
    ui->plainTextEdi_msgList->appendPlainText("$$$$$$$$$$$绑定端口成功$$$$$$$$$$$"+
                                               QString::number(udpServerObject->udp_socket->localPort()));

    connect(udpServerObject->udp_socket,&QUdpSocket::readyRead,this,[=](){
        readDatagramInfoFunc(ipAdr,port);
    });

    //命令按钮的切换
    ui->toolButton_start->setEnabled(false);
    ui->toolButton_connect->setEnabled(false);
    ui->toolButton_close->setEnabled(true);
}

//关闭监听
void UdpModule::on_toolButton_close_clicked()
{
    ui->toolButton_start->setEnabled(true);
    ui->toolButton_connect->setEnabled(true);
    ui->toolButton_close->setEnabled(false);


    udpServerObject->udp_socket->close();
    ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Turn off listening.\n");

}

//连接服务
void UdpModule::on_toolButton_connect_clicked()
{
    if(udpServerObject == nullptr)
    {
        return;
    }

    ui->plainTextEdi_msgList->clear();
    //初始化套接字，设置组播地址
    udpServerObject->udp_socket = new QUdpSocket;
    udpServerObject->udp_socket->close();//关闭UDP套接字

    ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Server connection successfully.\n");

    //命令按钮切换
    ui->toolButton_start->setEnabled(false);
    ui->toolButton_connect->setEnabled(false);
    ui->toolButton_disconnect->setEnabled(true);
    ui->toolButton_send->setEnabled(true);
    ui->plainTextEdit_sendMsg->setEnabled(true);
}

//断开服务
void UdpModule::on_toolButton_disconnect_clicked()
{
    //关闭udp套接字
    udpServerObject->udp_socket->close();

    //命令按钮切换
    ui->toolButton_start->setEnabled(true);
    ui->toolButton_connect->setEnabled(true);
    ui->toolButton_close->setEnabled(false);
    ui->toolButton_disconnect->setEnabled(false);
    ui->toolButton_send->setEnabled(false);
    ui->plainTextEdit_sendMsg->setEnabled(false);

    ui->plainTextEdi_msgList->appendPlainText("[Prompt]:Disconnect from Server.\n");
}

//发送消息
void UdpModule::on_toolButton_send_clicked()
{
    //获取当前时间
    QString currentTime = getCurrentDateTime();

    //初始化套接字，设置组播地址
    udpServerObject->udp_socket = new QUdpSocket;
    //IP地址
    QString ipAdr = ui->comboBox_ipAdr->currentText();
    udpServerObject->udp_hostAddress.setAddress(ipAdr);
    QHostAddress *hostAdr = new QHostAddress(ipAdr);
    //端口
    int port = ui->spinBox_port->text().toInt();
    //将读取消息回发给客户端

    QString strTemps = ui->plainTextEdit_sendMsg->toPlainText();
    QByteArray sendMsg = strTemps.toUtf8();
    udpServerObject->udp_socket->writeDatagram(sendMsg,*hostAdr,port);

    ui->plainTextEdi_msgList->appendPlainText("\n" + currentTime + "\nSending:" + sendMsg);

    connect(udpServerObject->udp_socket,&QUdpSocket::readyRead,this,[=](){
       readServerDatagramFunc(ipAdr,port);
    });
}



//退出程序
void UdpModule::on_toolButton_exit_clicked()
{
    this->close();
}


// 只管启动监听，读取消息 --服务器
void UdpModule::readDatagramInfoFunc(QString strIP, int iPort)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString year = QString::number(currentDateTime.date().year());
    QString month = QString::number(currentDateTime.date().month());
    QString day = QString::number(currentDateTime.date().day());
    QString hour = QString::number(currentDateTime.time().hour());
    QString minute = QString::number(currentDateTime.time().minute());
    QString second = QString::number(currentDateTime.time().second());
    QString strTemp = year + "-" + month + "-" + day + " "
            + hour + ":" + minute + ":" + second;
    QByteArray qba_data;
    qba_data.resize(udpServerObject->udp_socket->pendingDatagramSize());
    QHostAddress *hostIpAddress = new QHostAddress(strIP);
    quint16 int_port = iPort;

    while(udpServerObject->udp_socket->hasPendingDatagrams())
    {
        udpServerObject->udp_socket->readDatagram(qba_data.data(),qba_data.size(),hostIpAddress,&int_port);
        ui->plainTextEdi_msgList->appendPlainText("\n"+strTemp + "\nReceive:" + QString::fromLatin1(qba_data));

        //将读取到的信息回发给客户端
        QString strTemps = "[Prompt:Server reply Message]:";
        QByteArray qbtMsg = strTemps.toUtf8() + qba_data;

        //将收到数据报 回复到客户端
        udpServerObject->udp_socket->writeDatagram(qbtMsg,*hostIpAddress,int_port);
        ui->plainTextEdi_msgList->appendPlainText("Sending:" + qbtMsg);
    }
}

// 连接服务器，读取服务器回复消息 --客户端
void UdpModule::readServerDatagramFunc(QString strIP, int iPort)
{
    QByteArray qba_data;
    qba_data.resize(udpServerObject->udp_socket->pendingDatagramSize());
    QHostAddress *hostIpAddress = new QHostAddress(strIP);
    quint16 int_port = iPort;

    while(udpServerObject->udp_socket->hasPendingDatagrams())
    {
        udpServerObject->udp_socket->readDatagram(qba_data.data(),qba_data.size(),hostIpAddress,&int_port);
        ui->plainTextEdi_msgList->appendPlainText("Receive:" + QString::fromLatin1(qba_data));


    }
}

//获取当前时间
QString UdpModule::getCurrentDateTime()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString year = QString::number(currentDateTime.date().year());
    QString month = QString::number(currentDateTime.date().month());
    QString day = QString::number(currentDateTime.date().day());
    QString hour = QString::number(currentDateTime.time().hour());
    QString minute = QString::number(currentDateTime.time().minute());
    QString second = QString::number(currentDateTime.time().second());
    QString strTemp = year + "-" + month + "-" + day + " "
            + hour + ":" + minute + ":" + second;
    return strTemp;
}
